<!-- src/views/EditPostView.vue -->
<template>
  <div class="edit-post-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" content="编辑帖子" style="margin-bottom: 20px;" />

    <el-card v-if="post.id" class="edit-post-card">
      <el-form
        ref="postFormRef"
        :model="postForm"
        :rules="postRules"
        label-width="80px"
        @submit.prevent="submitPost"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <!-- 可以根据需要替换为富文本编辑器 -->
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="15"
            placeholder="请输入帖子内容..."
            maxlength="65535"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitPost" :loading="saving">保存修改</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div v-else class="error-message">
      <p>帖子未找到或加载失败。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getPostById, updatePost } from '@/services/postService';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

const postFormRef = ref();
const loading = ref(false);
const saving = ref(false);

const post = ref({
  id: null,
  title: '',
  content: '',
  authorId: null
  // ... 其他字段
});

const postForm = reactive({
  title: '',
  content: ''
});

const postRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 1, max: 255, message: '标题长度为 1 到 255 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 1, max: 65535, message: '内容长度不能超过 65535 个字符', trigger: 'blur' }
  ]
};

const postId = computed(() => route.params.id);

// 获取帖子详情用于编辑
const fetchPostForEdit = async () => {
  if (!postId.value) return;
  loading.value = true;
  try {
    const response = await getPostById(postId.value);
    post.value = response.data;
    // 将数据填充到表单
    postForm.title = post.value.title;
    postForm.content = post.value.content;

    // --- 权限检查 ---
    // 确保当前用户有权编辑此帖子 (作者或管理员)
    // 这通常在后端 API 会进行验证，前端也可以做一个初步判断
    if (post.value.authorId !== authStore.currentUser?.id && !authStore.currentUser?.roles?.includes('ADMIN')) { // 假设 ADMIN 角色
         ElMessage.warning('您无权编辑此帖子');
         router.back(); // 或者跳转到详情页
         return;
    }
    // --- ---
  } catch (error) {
    console.error('Failed to fetch post for editing:', error);
    ElMessage.error(error.response?.data?.message || '获取帖子失败');
    router.back(); // 获取失败也返回
  } finally {
    loading.value = false;
  }
};

// 提交编辑后的帖子
const submitPost = async () => {
  if (!postFormRef.value) return;
  await postFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      try {
        const response = await updatePost(postId.value, {
          title: postForm.title,
          content: postForm.content
        });
        console.log('Post updated:', response.data);
        ElMessage.success('帖子更新成功');
        // 跳转回帖子详情页
        router.push(`/posts/${postId.value}`);
      } catch (error) {
        console.error('Post update failed:', error);
        ElMessage.error(error.response?.data?.message || '更新失败');
      } finally {
        saving.value = false;
      }
    } else {
      console.log('Post form validation failed!');
      return false;
    }
  });
};

onMounted(() => {
  fetchPostForEdit();
});
</script>

<style scoped>
.edit-post-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}
.edit-post-card {
  /* 可以添加卡片样式 */
}
.error-message {
  text-align: center;
  color: #f56c6c;
  margin-top: 50px;
}
</style>
